package com.xuecheng.manage_media_processor.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/*
 * rabbitmq的配置类
 */
@Configuration
public class RabbitMQConfig {
    
    //交换机的名称
    private final static String EX_MEDIA_PROCESSTASK = "ex_media_processor";
    
    //队列名称，从配置文件中读取
    @Value("${xc-service-manage-media.mq.queue-media-video-processor}")
    private String queue_media_video_processtask;
    
    //视频处理路由
    @Value("${xc-service-manage-media.mq.routingkey-media-video}")
    private String routingkey_media_video;
    
    //消费者并发数量
    private static final int DEFAULT_CONCURRENT = 10;
    
    //注册交换机
    @Bean(EX_MEDIA_PROCESSTASK)
    public Exchange EX_MEDIA_VIDEOTASK() {
        return ExchangeBuilder.directExchange(EX_MEDIA_PROCESSTASK).durable(true).build();
    }
    
    //注册队列
    @Bean("queue_media_video_processtask")
    public Queue QUEUE_PROCESSTASK() {
        Queue queue = new Queue(queue_media_video_processtask,true,false,true);
        return queue;
    }
    
    //交换机绑定队列
    @Bean
    public Binding binding_queue_media_processtask(
            @Qualifier("queue_media_video_processtask") Queue queue,
            @Qualifier(EX_MEDIA_PROCESSTASK) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).
                with(routingkey_media_video).noargs();
    }
    
    //设置工厂，支持并发
    @Bean("customContainerFactory")
    public SimpleRabbitListenerContainerFactory containerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            ConnectionFactory connectionFactory){
        //new一个工厂对象
        SimpleRabbitListenerContainerFactory factory = new 
                SimpleRabbitListenerContainerFactory();
        //设置最大并发数量
        factory.setConcurrentConsumers(DEFAULT_CONCURRENT);
        factory.setMaxConcurrentConsumers(DEFAULT_CONCURRENT);
        //配置工厂
        configurer.configure(factory, connectionFactory);
        return factory;
    }
    
    
}
